<?php
/**
 * MVC 中的视图类
 */
class View extends Base
{
	/**
	 * 用来保存模板变量
	 *
	 * @var array
	 */
	protected $_vars = array();
	
	public $json = array();
	
	public function __construct()
	{
		$this->_vars['css'] = $this->_vars['js'] = $this->_vars['title'] = "";
	}

	/**
	 * 显示页面
	 */
	final public function show()
	{
		if(is_ajax()){
			unset($this->_vars['js'], $this->_vars['css'], $this->_vars['title']);
			echo json_encode($this->_vars);
			return ;
		}
		$trace = debug_backtrace();
		$_mod = str_replace("Controller", "", $trace[1]['class']);
		$_act = $trace[1]['function'];
		
		$this->addCss("common, jquery/boxy, $_mod/common, $_mod/$_act"); //添加全局CSS
		$this->addJs("jquery/jquery, jquery/boxy, jquery/hotkeys, common, $_mod/common, $_mod/$_act"); //添加全局JS
		
		extract($this->_vars);
		include APP_PATH . "/template/layout.php";
	}
	
	public function isEmpty()
	{
		return empty($this->_vars);
	}

	public function addJs($js)
	{
		$jss = explode(',', $js);
		$script = '';
		foreach($jss as $js){
			$js = trim($js);
			$script .= "<script type='text/javascript' src='" . APP_HOME . "/public/js/{$js}.js'></script>\r\n";
		}
		$this->_vars['js'] .= $script;
	}
	
	public function addCss($css)
	{
		$c = explode(",", $css);
		$style = '';
		foreach($c as $cs){
			$cs = trim($cs);
			$style .= "<link type='text/css' rel='stylesheet' href='" . APP_HOME . "/public/css/{$cs}.css' />\r\n";
		}
		$this->_vars['css'] .= $style;
	}

	/**
	 * 对模板变量进行赋值
	 *
	 * @param string $var
	 * @param mixed $val
	 */
	public function __set($var, $val)
	{
		$this->_vars[$var] = $val;
	}

	/**
	 * 取得模板变量的值
	 *
	 * @param string $var
	 * @return mixed
	 */
	public function __get($var)
	{
		if(isset($this->_vars[$var])){
			return $this->_vars[$var];
		}else{
			return ;
		}
	}
}